package tmt.usercenter.web.controller.validtor;

import com.tmt.spring.validation.TmtCommonValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import tmt.usercenter.web.domain.UserInfoConfig;
import tmt.usercenter.web.service.TmtUserService;
import tmt.usercenter.web.service.UserInfoConfigService;
import tmt.usercenter.web.vo.user.MobileValidateInfo;
import tmt.usercenter.web.vo.user.RegisterVo;

import java.lang.reflect.Field;
import java.util.Objects;

@Component
public class MobileValidateInfoValidator extends TmtCommonValidator<MobileValidateInfo> {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserInfoConfigService userInfoConfigService;

    @Autowired
    private TmtUserService userService;

    @Override
    public boolean supports(Class<?> clazz) {
        return MobileValidateInfo.class.equals(clazz);
    }

    @Override
    public String selectMethodName(MobileValidateInfo obj, Field field, String methodName) {
        return methodName;
    }

    @Override
    public void validate(Object target, Errors errors) {
        MobileValidateInfo mobileValidateInfo = (MobileValidateInfo) target;
        if (!passwordEncoder.matches(mobileValidateInfo.getReceivedCode(), mobileValidateInfo.getSendCode())){
            errors.rejectValue("receivedCode", "error.MobileValidateInfo.receivedCode", "输入的验证码无效");
        }
    }

    @Override
    public boolean isRepeated(Object obj, String fieldName, Object fieldValue, boolean repeatable) {
        boolean exists = false;
        try {
            MobileValidateInfo mvInfo = (MobileValidateInfo) obj;

            UserInfoConfig userInfoConfig = userInfoConfigService.loadEntity(UserInfoConfig.class,"findByOriginSystemClientId",
                    new Object[]{mvInfo.getClientId(), false}, "1");

            if (userInfoConfig.getUniqueFields().contains(fieldName)) {
                switch (fieldName) {
                    case "mobile":
                        exists = userService.existsInClientSystemBy(userInfoConfig.getOriginSystem().getClientId(),
                                fieldName, mvInfo.getMobile(), mvInfo.getUserId());
                        break;
                }
            }
        }catch (Exception ignored){
            exists = repeatable;
        }
        return exists;
    }
}